var PRO=PRO||{};
PRO.statistics=(function(type){
	//ztree配置
	var setting = {data:{simpleData:{enable:true,idKey:"id",pIdKey:"pId",rootPId:'0'}},
			callback:{onClick:function(event, treeId, treeNode){
					var id = treeNode.id == '0' ? '' :treeNode.id;
					var type="(部门)";
					$("#target_title").attr("data-office-oruser","office");
					if(treeNode.pId==0){
						type="(公司)";
						$("#target_title").attr("data-office-oruser","company");
					}
					$("#target_title").text(treeNode.name+type+"统计数据");
					$("#target_title").attr("data-office-id",treeNode.pId);
				
					$('#officeContent').attr("src",WEBROOT.ctx+"/sys/statistics/userlist?office.id="+id+"&office.name="+treeNode.name);
					//查询统计数据
					var rangeType;
					$(".charts-choose-range").each(function(index){
				           if($(this).hasClass("active")){
				        	   rangeType=$(this).data("range");
				           }
				    })  
					var param=buildParam(rangeType);
					param.officeId=id;
					
					PRO.charts.initHistogramChart(WEBROOT.ctx+"/sys/statistics/ajaxGetHistogramData",param,$("#charts"));
				}
			}
		};
	function refreshTree(){
		$.getJSON(WEBROOT.ctx+"/sys/statistics/treeData",function(data){
			$.fn.zTree.init($("#ztree"), setting, data).expandAll(true);
		});
		$('#officeContent').attr("src",WEBROOT.ctx+"/sys/statistics/userlist");
	
	}
	function clearParam(type){
		if(type=="1"){
			$("#day_range").find("input").val("");
		}
		else if(type=="2"){
			$("#week_range").find("input").val("");
		}else{
			$("#month_range").find("input").val("");
		}
	}
	function buildParam(rangeType){
		var param={};
		param.rangeType=rangeType;
		if(rangeType=="1"){
			var startDate=$("input[name='startDate']").val();
			var endDate=$("input[name='endDate']").val();
			if(!startDate){
				alert("请输入开始日期！");
				return false;
			}
			if(!endDate){
				alert("请输入结束日期！");
				return false;
			}
			var d1 = new Date(startDate.replace(/\-/g, "\/"));  
			var d2 = new Date(endDate.replace(/\-/g, "\/"));  
			if ( d1 > d2) {
				alert("开始日期不能大于结束日期！");
				return false;
			}
			param.startDate=startDate.replace(/-/g,"");
			param.endDate=endDate.replace(/-/g,"");
			param.officeId=$("#target_title").attr("data-office-id");
			param.userId=$("#target_title").attr("data-user-id");
			param.officeOrUser=$("#target_title").attr("data-office-oruser");
		}
		else if(rangeType=="2"){
			var startWeek=$("input[name='startWeek']").data("week");
			var endWeek=$("input[name='endWeek']").data("week");
			
			var startDate=$("input[name='startWeek']").attr("data-date");
			var endDate=$("input[name='endWeek']").attr("data-date");
			
			param.startDate=startDate.replace(/-/g,"");
			param.endDate=endDate.replace(/-/g,"");
			
			param.officeId=$("#target_title").attr("data-office-id");
			param.userId=$("#target_title").attr("data-user-id");
			param.officeOrUser=$("#target_title").attr("data-office-oruser");
		}else{
			var startDate=$("input[name='startMonth']").val();
			var endDate=$("input[name='endMonth']").val();
			if(!startDate){
				alert("请输入开始月份！");
				return false;
			}
			if(!endDate){
				alert("请输入结束月份！");
				return false;
			}
			var d1 = new Date(startDate.replace(/\-/g, "\/"));  
			var d2 = new Date(endDate.replace(/\-/g, "\/"));  
			if ( d1 > d2) {
				alert("开始月份不能大于结束月份！");
				$("input[name='startMonth']").val("")
				$("input[name='startMonth']").val("")
				return false;
			}
			param.startDate=startDate.replace(/-/g,"");
			param.endDate=endDate.replace(/-/g,"");
			param.officeId=$("#target_title").attr("data-office-id");
			param.userId=$("#target_title").attr("data-user-id");
			param.officeOrUser=$("#target_title").attr("data-office-oruser");
		}
		param.statisticsType=$("#officeContentHidden").data("type");
		return param;
	}
	/**
	 * 获取当前月的第一天
	 */
	function getCurrentMonthFirst(){
	 var date=new Date();
	 date.setDate(1);
	 return date;
	}
	/**
	 * 获取当前月的最后一天
	 */
	function getCurrentMonthLast(){
	 var date=new Date();
	 var currentMonth=date.getMonth();
	 var nextMonth=++currentMonth;
	 var nextMonthFirstDay=new Date(date.getFullYear(),nextMonth,1);
	 var oneDay=1000*60*60*24;
	 return new Date(nextMonthFirstDay-oneDay);
	}
	//动态绑定事件
	function bindEvents(){
		//统计类型切换（按天 周 月）
		$(".charts-choose-range").click(function(){
			var rangeType=$(this).data("range");
			if(rangeType=="1"){
				$("#day_range").show();
				$("#week_range").hide();
				$("#month_range").hide();
			}
			else if(rangeType=="2"){
				$("#day_range").hide();
				$("#week_range").show();
				$("#month_range").hide();
			}else{
				$("#day_range").hide();
				$("#week_range").hide();
				$("#month_range").show();
			}
			$(".charts-choose-range").removeClass("active");
			$(this).addClass("active");
			var param=buildParam(rangeType);
			PRO.charts.initHistogramChart(WEBROOT.ctx+"/sys/statistics/ajaxGetHistogramData",param,$("#charts"));
		});
		$(".week").focus(function(){
			var that=$(this);
			WdatePicker({
				isShowWeek : true,
				errDealMode:3,
				weekMethod:"MSExcel",
				onpicked : function() {
					var year=$dp.cal.getDateStr('yyyy')
					var week=$dp.cal.getP('W', 'W');
					var d=$dp.cal.getDateStr('yyyy-MM-dd')
					that.val(year+"年第"+week+"周");
					that.attr("data-week",year+week+"");
					that.attr("data-date",d);
					var startWeek=$("input[name='startWeek']").data("week");
					var endWeek=$("input[name='endWeek']").data("week");
					var startDate=$("input[name='startWeek']").attr("data-date");
					var endDate=$("input[name='endWeek']").attr("data-date");
					var d1,d2;
					if(startDate){
						 d1 = startWeek.replace(/\-/g, "\/");  
					}
					if(endDate){
						 d2 = endWeek.replace(/\-/g, "\/");  
					}
					if ((d1&&d2)&&(d1>d2)) {
						alert("开始周数不能大于结束周数！");
						return false;
					}else if(d1&&d2){
						  if(DateDiff(startDate,endDate)>10){
							  alert("最大只能查询十周以内的数据哦！");
							  return;
						  }
						var param=buildParam("2");
						PRO.charts.initHistogramChart(WEBROOT.ctx+"/sys/statistics/ajaxGetHistogramData",param,$("#charts"));
					}
				}
			})
		});
		$(".day").focus(function(){
			var that=$(this);
			WdatePicker({
				onpicked : function() {
					var startDate=$("input[name='startDate']").val();
					var endDate=$("input[name='endDate']").val();
					var d1,d2;
					if(startDate){
						 d1 = new Date(startDate.replace(/\-/g, "\/"));  
					}
					if(endDate){
						 d2 = new Date(endDate.replace(/\-/g, "\/"));  
					}
					if ((d1&&d2)&&(d1>d2)) {
						alert("开始天数不能大于结束天数！");
						return false;
					}else if(d1&&d2){
						  if(DateDiff(startDate,endDate)>29){
							  alert("最大只能查询三十天的数据哦！");
							  return;
						  }
						var param=buildParam("1");
						PRO.charts.initHistogramChart(WEBROOT.ctx+"/sys/statistics/ajaxGetHistogramData",param,$("#charts"));
					}
				}
			})
		});
		$(".month").focus(function(){
			var that=$(this);
			WdatePicker({
				dateFmt:'yyyy-MM',
				onpicked : function() {
					var startMonth=$("input[name='startMonth']").val();
					var endMonth=$("input[name='endMonth']").val();
					var d1,d2;
					if(startMonth){
						 d1 = new Date(startMonth.replace(/\-/g, "\/"));  
					}
					if(endMonth){
						 d2 = new Date(endMonth.replace(/\-/g, "\/"));  
					}
					if ((d1&&d2)&&(d1>d2)) {
						alert("开始月份数不能大于结束月份！");
						return false;
					}else if(d1&&d2){
						 var number = 0;      
					      var yearToMonth = (d2.getFullYear() - d1.getFullYear()) * 12;      
					      number += yearToMonth;      
					      monthToMonth = d2.getMonth() - d1.getMonth();      
					      number += monthToMonth;      
						  if(number>11){
							  alert("最大只能查询十二个月内的数据哦！");
							  return;
						  }
						var param=buildParam("3");
						PRO.charts.initHistogramChart(WEBROOT.ctx+"/sys/statistics/ajaxGetHistogramData",param,$("#charts"));
					}
				}
			})
		});
		$("#officeContentHidden").bind("click",function(){
			//查询统计数据
			var rangeType;
			$(".charts-choose-range").each(function(index){
		           if($(this).hasClass("active")){
		        	   rangeType=$(this).data("range");
		           }
		    })  
			var param=buildParam(rangeType);
			PRO.charts.initHistogramChart(WEBROOT.ctx+"/sys/statistics/ajaxGetHistogramData",param,$("#charts"));
		});
		$("#switch").click(function(){
			if($("#left_table").hasClass("hide")){
				alert(1)
				$("#left_table").removeClass("hide");
				$("#right_table").removeClass("hide");
				
				$("#left").addClass("hide");
				$("#right").addClass("hide");
			}else{
				$("#left").removeClass("hide");
				$("#right").removeClass("hide");
				
				$("#left_table").addClass("hide");
				$("#right_table").addClass("hide");
			}
		});
	}
	  //计算天数差的函数，通用  
	   function  DateDiff(sDate1,  sDate2){    //sDate1和sDate2是2006-12-18格式  
	       var  aDate,  oDate1,  oDate2,  iDays  ;
	       aDate  =  sDate1.split("-")  ;
	       oDate1  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])  ;  //转换为12-18-2006格式  
	       aDate  =  sDate2.split("-")  ;
	       oDate2  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])  ;
	       iDays  =  parseInt(Math.abs(oDate1  -  oDate2)  /  1000  /  60  /  60  /24) ;   //把相差的毫秒数转换为天数  
	       return  iDays  ;
	   }    

	//初始化ztree
	function initZtree(){
			refreshTree();
			var leftWidth = 180; // 左侧窗口大小
			var htmlObj = $("html"), mainObj = $("#main");
			var frameObj = $("#left, #openClose, #right, #right iframe");
			function wSize(){
				var strs = getWindowSize().toString().split(",");
				htmlObj.css({"overflow-x":"hidden", "overflow-y":"hidden"});
				mainObj.css("width","auto");
				frameObj.height(strs[0] - 5);
				var leftWidth = ($("#left").width() < 0 ? 0 : $("#left").width());
				$("#right").width($("#content").width()- leftWidth - $("#openClose").width() -5);
				$(".ztree").width(leftWidth - 10).height(frameObj.height() - 46);
			}
	}
	return {
		//页面初始化
		init:function(){
			initZtree();
			bindEvents();
			//初始化柱状图
			var param=buildParam("1");
			PRO.charts.initHistogramChart(WEBROOT.ctx+"/sys/statistics/ajaxGetHistogramData",param,$("#charts"));
		},buildParam:function(type){
			buildParam(type);
		}
	}
})();
$(function(){
	PRO.statistics.init();
})
	